<template>
  <div class="chuandao-test-container">
    <!-- 页面标题和说明 -->
    <div class="header-section">
      <div class="title-wrapper">
        <h2 class="page-title">
          <i class="el-icon-cpu"></i>
          船到模拟测试
        </h2>
        <el-tag type="warning" effect="dark" size="small">仅测试环境可用</el-tag>
      </div>
      <p class="page-description">
        模拟船到订单状态变更，测试回调通知功能。支持单个订单测试和批量测试，可配置回调URL进行真实推送验证。
      </p>
    </div>

    <!-- 测试配置面板 -->
    <el-card class="config-card" shadow="never">
      <div slot="header" class="card-header">
        <span><i class="el-icon-setting"></i> 测试配置</span>
        <el-button type="text" @click="loadTestConfig" :loading="configLoading">
          <i class="el-icon-refresh"></i> 刷新配置
        </el-button>
      </div>

      <el-row :gutter="20">
        <el-col :span="12">
          <div class="config-item">
            <label>测试模式状态：</label>
            <el-tag :type="testConfig.test_mode_enabled ? 'success' : 'danger'" size="small">
              {{ testConfig.test_mode_enabled ? '已启用' : '未启用' }}
            </el-tag>
          </div>
          <div class="config-item">
            <label>调试模式状态：</label>
            <el-tag :type="testConfig.app_debug_enabled ? 'success' : 'danger'" size="small">
              {{ testConfig.app_debug_enabled ? '已启用' : '未启用' }}
            </el-tag>
          </div>
          <div class="config-item">
            <label>API域名：</label>
            <span>{{ testConfig.api_domain }}</span>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="config-item">
            <label>回调端点：</label>
            <span>{{ testConfig.callback_endpoint }}</span>
          </div>
          <div class="config-item">
            <label>最大批量测试数：</label>
            <span>{{ testConfig.max_batch_size }}</span>
          </div>
          <div class="config-item">
            <label>频率限制：</label>
            <span>{{ (testConfig.rate_limit && testConfig.rate_limit.max_requests) || 0 }}/{{ (testConfig.rate_limit && testConfig.rate_limit.window) || 0 }}秒</span>
          </div>
        </el-col>
      </el-row>
      
      <!-- Token状态面板 -->
      <el-divider content-position="left">
        <span style="color: #666; font-size: 14px;">
          <i class="el-icon-key"></i> Access Token 状态
        </span>
      </el-divider>
      
      <el-row :gutter="20">
        <el-col :span="16">
          <div class="config-item">
            <label>Token状态：</label>
            <el-tag 
              :type="getTokenStatusType()" 
              size="small"
              :loading="tokenStatusLoading">
              {{ getTokenStatusText() }}
            </el-tag>
            <span v-if="tokenStatus.token_preview" style="margin-left: 10px; color: #999; font-size: 12px;">
              ({{ tokenStatus.token_preview }})
            </span>
          </div>
          <div class="config-item" v-if="tokenStatus.checked_at">
            <label>检查时间：</label>
            <span style="color: #999; font-size: 12px;">{{ tokenStatus.checked_at }}</span>
          </div>
          <div class="config-item" v-if="tokenStatus.message && tokenStatus.status !== 'valid'">
            <label>状态说明：</label>
            <span style="color: #f56c6c; font-size: 12px;">{{ tokenStatus.message }}</span>
          </div>
        </el-col>
        <el-col :span="8" style="text-align: right;">
          <el-button 
            type="primary" 
            size="small" 
            @click="checkTokenStatus"
            :loading="tokenStatusLoading">
            <i class="el-icon-refresh"></i> 检查状态
          </el-button>
          <el-button 
            type="warning" 
            size="small" 
            @click="refreshToken"
            :loading="tokenRefreshLoading"
            :disabled="tokenStatus.status === 'valid'">
            <i class="el-icon-refresh-right"></i> 刷新Token
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 单个测试面板 -->
    <el-card class="test-panel-card" shadow="never">
      <div slot="header" class="card-header">
        <span><i class="el-icon-cpu"></i> 单个订单模拟测试</span>
      </div>

      <el-form :model="testForm" :rules="testRules" ref="testForm" label-width="140px">
        <!-- Access Token 单独一行 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="Access Token" prop="access_token">
              <el-input v-model="testForm.access_token" placeholder="请输入商户访问令牌" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 订单号 一行显示 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="订单号" prop="order_identifier">
              <el-select v-model="orderNoType" placeholder="选择类型" style="width: 140px; margin-right: 10px;">
                <el-option label="船到订单号" value="order_no"></el-option>
                <el-option label="第三方订单号" value="origin_order_no"></el-option>
              </el-select>
              <el-input v-model="testForm.order_identifier" placeholder="输入订单号" clearable style="width: calc(100% - 150px);" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 订单状态和订单子状态 一行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="订单状态" prop="order_state" style="display: inline-block; width: 48%; margin-right: 2%;">
              <el-select v-model="testForm.order_state" placeholder="选择订单状态" @change="onOrderStateChange">
                <el-option
                  v-for="state in orderStates"
                  :key="state.state"
                  :label="`${state.state} - ${state.name}`"
                  :value="state.state">
                  <span style="float: left">{{ state.state }} - {{ state.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ state.description }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="订单子状态" prop="order_sub_state" style="display: inline-block; width: 48%;" 
                          v-if="testForm.order_state === '4' || testForm.order_state === '-1'">
              <el-select v-model="testForm.order_sub_state" placeholder="选择子状态">
                <el-option
                  v-for="subState in currentSubStates"
                  :key="subState.sub_state"
                  :label="`${subState.sub_state} - ${subState.name}`"
                  :value="subState.sub_state">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 回调URL 单独一行 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="回调URL" prop="callback_url">
              <el-input v-model="testForm.callback_url" placeholder="请输入回调通知URL" clearable>
                <el-button slot="append" @click="validateCallbackUrl" :loading="urlValidating">
                  <i class="el-icon-check"></i> 验证
                </el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 操作按钮 -->
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="executeTest" :loading="testing">
                <i class="el-icon-video-play"></i> 执行测试
              </el-button>
              <el-button @click="resetTestForm">
                <i class="el-icon-refresh"></i> 重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 批量测试面板 -->
    <el-card class="batch-test-card" shadow="never">
      <div slot="header" class="card-header">
        <span><i class="el-icon-s-grid"></i> 批量模拟测试</span>
        <div>
          <el-button type="text" @click="addBatchTestCase">
            <i class="el-icon-plus"></i> 添加测试用例
          </el-button>
          <el-button type="text" @click="clearBatchTestCases">
            <i class="el-icon-delete"></i> 清空
          </el-button>
        </div>
      </div>

      <div v-if="batchTestCases.length > 0">
        <div v-for="(testCase, index) in batchTestCases" :key="index" class="batch-test-case">
          <div class="test-case-header">
            <span>测试用例 {{ index + 1 }}</span>
            <el-button type="text" @click="removeBatchTestCase(index)" style="color: #f56c6c;">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </div>
          
          <el-row :gutter="20">
            <el-col :span="6">
              <el-input v-model="testCase.order_identifier" placeholder="订单号" size="small" />
            </el-col>
            <el-col :span="4">
              <el-select v-model="testCase.order_state" placeholder="状态" size="small" @change="onBatchOrderStateChange(testCase.order_state, index)">
                <el-option
                  v-for="state in orderStates"
                  :key="state.state"
                  :label="state.name"
                  :value="state.state">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4" v-if="testCase.order_state === '4' || testCase.order_state === '-1'">
              <el-select v-model="testCase.order_sub_state" placeholder="子状态" size="small">
                <el-option
                  v-for="subState in (testCase.availableSubStates || [{sub_state: '0', name: '默认'}])"
                  :key="subState.sub_state"
                  :label="subState.sub_state + ' - ' + subState.name"
                  :value="subState.sub_state">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="10">
              <el-input v-model="testCase.callback_url" placeholder="回调URL（可选，使用默认）" size="small" />
            </el-col>
          </el-row>
        </div>

        <div class="batch-test-actions">
          <el-button type="primary" @click="executeBatchTest" :loading="batchTesting">
            <i class="el-icon-video-play"></i> 执行批量测试
          </el-button>
          <span class="test-case-count">共 {{ batchTestCases.length }} 个测试用例</span>
        </div>
      </div>

      <div v-else class="empty-batch-test">
        <i class="el-icon-s-grid"></i>
        <p>暂无批量测试用例</p>
        <el-button type="text" @click="addBatchTestCase">添加第一个测试用例</el-button>
      </div>
    </el-card>

    <!-- 测试结果面板 -->
    <el-card v-if="testResult" class="result-card" shadow="never">
      <div slot="header" class="card-header">
        <span><i class="el-icon-document"></i> 测试结果</span>
        <el-button type="text" @click="clearTestResult">
          <i class="el-icon-close"></i> 清除
        </el-button>
      </div>

      <div class="test-result-content">
        <div class="result-status">
          <el-tag :type="testResult.success ? 'success' : 'danger'" size="medium">
            {{ testResult.success ? '测试成功' : '测试失败' }}
          </el-tag>
          <span class="execution-time">执行时间: {{ testResult.execution_time }}ms</span>
        </div>

        <el-tabs v-model="resultActiveTab" type="border-card">
          <el-tab-pane label="请求数据" name="request">
            <pre class="json-content">{{ JSON.stringify(testResult.request_data, null, 2) }}</pre>
          </el-tab-pane>
          <el-tab-pane label="响应数据" name="response">
            <pre class="json-content">{{ JSON.stringify(testResult.response_data, null, 2) }}</pre>
          </el-tab-pane>
          <el-tab-pane label="回调信息" name="callback" v-if="testResult.callback_response">
            <pre class="json-content">{{ JSON.stringify(testResult.callback_response, null, 2) }}</pre>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <!-- 测试历史面板 -->
    <el-card class="history-card" shadow="never">
      <div slot="header" class="card-header">
        <span><i class="el-icon-time"></i> 测试历史</span>
        <div>
          <el-button type="text" @click="loadTestHistory">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
          <el-button type="text" @click="clearTestHistory">
            <i class="el-icon-delete"></i> 清理历史
          </el-button>
        </div>
      </div>

      <el-table :data="testHistory" stripe style="width: 100%" v-loading="historyLoading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="test_type" label="测试类型" width="160" />
        <el-table-column label="测试参数" min-width="200">
          <template slot-scope="scope">
            <div v-if="scope.row.request_data">
              <div>状态: {{ scope.row.request_data.order_state }}</div>
              <div>订单: {{ scope.row.request_data.order_no || scope.row.request_data.origin_order_no }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'success' ? 'success' : scope.row.status === 'failed' ? 'danger' : 'warning'" size="small">
              {{ scope.row.status === 'success' ? '成功' : scope.row.status === 'failed' ? '失败' : '运行中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="execution_time" label="执行时间" width="100">
          <template slot-scope="scope">
            {{ scope.row.execution_time }}ms
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewTestDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          @current-change="handlePageChange"
          :current-page="historyPagination.page"
          :page-size="historyPagination.limit"
          :total="historyPagination.total"
          layout="total, prev, pager, next">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getChuandaoTestConfig, simulateCallback, batchSimulateCallback, validateCallbackUrl, getTestHistory, clearTestHistory, getOrderStates, getTokenStatus, refreshToken, getFullToken } from '@/api/chuandao/test'

export default {
  name: 'ChuandaoTest',
  data() {
    return {
      // 测试配置
      testConfig: {
        test_mode_enabled: false,
        app_debug_enabled: false,
        api_domain: '',
        callback_endpoint: '',
        max_batch_size: 10,
        rate_limit: { max_requests: 10, window: 60 }
      },
      configLoading: false,

      // 单个测试表单
      testForm: {
        access_token: '',
        order_identifier: '',
        order_state: '',
        order_sub_state: '', // 初始化为空，由订单状态变更时自动设置
        callback_url: ''
      },
      orderNoType: 'order_no',
      
      // 表单验证规则
      testRules: {
        access_token: [
          { required: true, message: '请输入Access Token', trigger: 'blur' }
        ],
        order_identifier: [
          { required: true, message: '请输入订单号', trigger: 'blur' }
        ],
        order_state: [
          { required: true, message: '请选择订单状态', trigger: 'change' }
        ],
        callback_url: [
          { required: true, message: '请输入回调URL', trigger: 'blur' },
          { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' }
        ]
      },

      // 订单状态
      orderStates: [],
      currentSubStates: [], // 初始化为空，由订单状态选择时填充

      // 测试状态
      testing: false,
      urlValidating: false,

      // 批量测试
      batchTestCases: [],
      batchTesting: false,

      // 测试结果
      testResult: null,
      resultActiveTab: 'request',

      // 测试历史
      testHistory: [],
      historyLoading: false,
      historyPagination: {
        page: 1,
        limit: 10,
        total: 0
      },

      // Token状态管理
      tokenStatus: {
        status: 'unknown',
        message: '未检查',
        merchant_id: 1,
        token_preview: null,
        checked_at: null
      },
      tokenStatusLoading: false,
      tokenRefreshLoading: false
    }
  },

  computed: {
    
  },

  mounted() {
    this.initData()
  },

  methods: {
    // 初始化数据
    async initData() {
      await this.loadTestConfig()
      await this.loadOrderStates()
      await this.loadTestHistory()
      // 自动检查Token状态
      await this.checkTokenStatus()
    },

    // 加载测试配置
    async loadTestConfig() {
      this.configLoading = true
      try {
        const response = await getChuandaoTestConfig()
        if (response.code === 0) {
          this.testConfig = response.data
          // 设置默认回调URL
          if (this.testConfig.default_callback_url && !this.testForm.callback_url) {
            this.testForm.callback_url = this.testConfig.default_callback_url
          }
          // 设置默认Access Token（从token状态中获取）
          if (this.testConfig.token_status && this.testConfig.token_status.status === 'valid' && !this.testForm.access_token) {
            // 获取完整的token（不是预览版本）
            await this.setDefaultAccessToken()
          }
        }
      } catch (error) {
        this.$message.error('加载测试配置失败')
      } finally {
        this.configLoading = false
      }
    },

    // 加载订单状态列表
    async loadOrderStates() {
      try {
        const response = await getOrderStates()
        if (response.code === 0) {
          this.orderStates = response.data
        }
      } catch (error) {
        this.$message.error('加载订单状态失败')
      }
    },

    // 订单状态变更
    onOrderStateChange(state) {
      const selectedState = this.orderStates.find(s => s.state === state)
      if (selectedState) {
        this.currentSubStates = selectedState.sub_states || [{ sub_state: '0', name: '默认子状态' }]
        // 自动选择第一个可用的子状态，确保符合船到数据字典规范
        this.testForm.order_sub_state = selectedState.sub_states[0]?.sub_state || '0'
      }
    },

    // 批量测试订单状态变更
    onBatchOrderStateChange(state, index) {
      const selectedState = this.orderStates.find(s => s.state === state)
      if (selectedState && this.batchTestCases[index]) {
        // 为特定测试用例设置可用的子状态
        this.$set(this.batchTestCases[index], 'availableSubStates', 
          selectedState.sub_states || [{ sub_state: '0', name: '默认子状态' }])
        // 自动选择第一个可用的子状态
        this.batchTestCases[index].order_sub_state = selectedState.sub_states[0]?.sub_state || '0'
      }
    },

    // 验证回调URL
    async validateCallbackUrl() {
      if (!this.testForm.callback_url) {
        this.$message.warning('请先输入回调URL')
        return
      }

      this.urlValidating = true
      try {
        const response = await validateCallbackUrl({ callback_url: this.testForm.callback_url })
        if (response.code === 0) {
          const result = response.data
          if (result.reachable) {
            this.$message.success(`URL可达，响应时间: ${result.response_time}ms`)
          } else {
            this.$message.warning(`URL不可达: ${result.error}`)
          }
        }
      } catch (error) {
        this.$message.error('URL验证失败')
      } finally {
        this.urlValidating = false
      }
    },

    // 执行单个测试
    async executeTest() {
      this.$refs.testForm.validate(async (valid) => {
        if (!valid) return

        this.testing = true
        let params = null
        try {
          params = {
            access_token: this.testForm.access_token,
            order_state: this.testForm.order_state,
            order_sub_state: this.testForm.order_sub_state,
            callback_url: this.testForm.callback_url
          }

          // 设置订单号参数
          if (this.orderNoType === 'order_no') {
            params.order_no = this.testForm.order_identifier
          } else {
            params.origin_order_no = this.testForm.order_identifier
          }

          const response = await simulateCallback(params)
          
          if (response.code === 0) {
            this.testResult = {
              success: true,
              ...response.data
            }
            this.$message.success('模拟测试执行成功')
            this.loadTestHistory() // 刷新历史记录
          } else {
            this.testResult = {
              success: false,
              error: response.message,
              request_data: params
            }
            this.$message.error(`测试失败: ${response.message}`)
          }
        } catch (error) {
          this.testResult = {
            success: false,
            error: error.message,
            request_data: params
          }
          this.$message.error('测试执行异常')
        } finally {
          this.testing = false
        }
      })
    },

    // 重置测试表单
    resetTestForm() {
      this.$refs.testForm.resetFields()
      this.testForm.order_identifier = ''
      this.orderNoType = 'order_no'
    },

    // 添加批量测试用例
    addBatchTestCase() {
      const defaultState = this.orderStates.find(s => s.state === '1')
      const availableSubStates = defaultState?.sub_states || [{ sub_state: '0', name: '默认子状态' }]
      
      this.batchTestCases.push({
        order_identifier: '',
        order_state: '1',
        order_sub_state: availableSubStates[0]?.sub_state || '0',
        callback_url: this.testConfig.default_callback_url || '',
        availableSubStates: availableSubStates
      })
    },

    // 删除批量测试用例
    removeBatchTestCase(index) {
      this.batchTestCases.splice(index, 1)
    },

    // 清空批量测试用例
    clearBatchTestCases() {
      this.batchTestCases = []
    },

    // 执行批量测试
    async executeBatchTest() {
      if (this.batchTestCases.length === 0) {
        this.$message.warning('请先添加测试用例')
        return
      }

      // 验证测试用例
      for (let i = 0; i < this.batchTestCases.length; i++) {
        const testCase = this.batchTestCases[i]
        if (!testCase.order_identifier || !testCase.order_state) {
          this.$message.error(`测试用例 ${i + 1} 参数不完整`)
          return
        }
      }

      this.batchTesting = true
      try {
        // 转换测试用例格式
        const testCases = this.batchTestCases.map(testCase => {
          const params = {
            access_token: this.testForm.access_token,
            order_state: testCase.order_state,
            order_sub_state: testCase.order_sub_state,
            callback_url: testCase.callback_url || this.testConfig.default_callback_url
          }

          // 设置订单号（这里简化处理，都按order_no处理）
          params.order_no = testCase.order_identifier

          return params
        })

        const response = await batchSimulateCallback({ test_cases: testCases })
        
        if (response.code === 0) {
          const result = response.data
          this.$message.success(`批量测试完成: 成功 ${result.success_count}，失败 ${result.failed_count}`)
          this.testResult = {
            success: true,
            batch_result: result
          }
          this.loadTestHistory() // 刷新历史记录
        } else {
          this.$message.error(`批量测试失败: ${response.message}`)
        }
      } catch (error) {
        this.$message.error('批量测试执行异常')
      } finally {
        this.batchTesting = false
      }
    },

    // 清除测试结果
    clearTestResult() {
      this.testResult = null
    },

    // 加载测试历史
    async loadTestHistory() {
      this.historyLoading = true
      try {
        const response = await getTestHistory({
          page: this.historyPagination.page,
          limit: this.historyPagination.limit
        })
        
        if (response.code === 0) {
          this.testHistory = response.data
          this.historyPagination.total = response.count
        }
      } catch (error) {
        this.$message.error('加载测试历史失败')
      } finally {
        this.historyLoading = false
      }
    },

    // 分页变更
    handlePageChange(page) {
      this.historyPagination.page = page
      this.loadTestHistory()
    },

    // 查看测试详情
    viewTestDetail(row) {
      this.$msgbox({
        title: '测试详情',
        message: `<pre style="max-height: 70vh; overflow-y: auto; padding: 16px; background-color: #F5F7FA; border-radius: 4px; border: 1px solid #EBEEF5; font-family: 'Courier New', monospace; font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-all; margin: 0;">${JSON.stringify(row, null, 2)}</pre>`,
        dangerouslyUseHTMLString: true,
        customClass: 'test-detail-dialog',
        showCancelButton: false,
        confirmButtonText: '关闭'
      })
    },

    // 清理测试历史
    async clearTestHistory() {
      try {
        await this.$confirm('确定要清理30天前的测试历史记录吗？', '确认', {
          type: 'warning'
        })

        const response = await clearTestHistory()
        if (response.code === 0) {
          this.$message.success(`清理完成，删除了 ${response.data.cleared_count} 条记录`)
          this.loadTestHistory()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('清理历史记录失败')
        }
      }
    },

    // Token状态相关方法

    // 检查Token状态
    async checkTokenStatus() {
      this.tokenStatusLoading = true
      try {
        const response = await getTokenStatus()
        if (response.code === 0) {
          this.tokenStatus = response.data
        } else {
          this.tokenStatus = {
            status: 'error',
            message: response.message || '获取Token状态失败',
            merchant_id: 1,
            token_preview: null,
            checked_at: new Date().toLocaleString()
          }
        }
      } catch (error) {
        this.tokenStatus = {
          status: 'error',
          message: '网络错误或服务不可用',
          merchant_id: 1,
          token_preview: null,
          checked_at: new Date().toLocaleString()
        }
        this.$message.error('检查Token状态失败')
      } finally {
        this.tokenStatusLoading = false
      }
    },

    // 刷新Token
    async refreshToken() {
      this.tokenRefreshLoading = true
      try {
        const response = await refreshToken()
        if (response.code === 0) {
          this.$message.success('Token刷新成功')
          // 刷新成功后重新检查状态
          await this.checkTokenStatus()
        } else {
          this.$message.error(`Token刷新失败: ${response.message}`)
        }
      } catch (error) {
        this.$message.error('Token刷新异常')
      } finally {
        this.tokenRefreshLoading = false
      }
    },

    // 获取Token状态类型（用于el-tag的type属性）
    getTokenStatusType() {
      switch (this.tokenStatus.status) {
        case 'valid':
          return 'success'
        case 'invalid':
          return 'warning'
        case 'error':
          return 'danger'
        default:
          return 'info'
      }
    },

    // 获取Token状态文本
    getTokenStatusText() {
      switch (this.tokenStatus.status) {
        case 'valid':
          return '✅ 有效'
        case 'invalid':
          return '⚠️ 已过期'
        case 'error':
          return '❌ 错误'
        case 'unknown':
        default:
          return '🔍 未检查'
      }
    },

    // 设置默认Access Token
    async setDefaultAccessToken() {
      try {
        // 调用新的API获取完整的access token
        const response = await getFullToken()
        if (response.code === 0 && response.data.status === 'success') {
          // 填入真正的access token
          this.testForm.access_token = response.data.access_token
          this.$message.success('已自动填入默认Access Token')
        } else {
          // 如果获取失败，保持空白并提示用户手动输入
          console.log('获取完整token失败:', response.message)
        }
      } catch (error) {
        // 如果API调用失败，保持空白并提示用户手动输入
        console.log('获取默认token异常:', error)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.chuandao-test-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 84px);

  .header-section {
    background: white;
    padding: 24px;
    border-radius: 6px;
    margin-bottom: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .title-wrapper {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 12px;

      .page-title {
        margin: 0;
        font-size: 24px;
        color: #303133;
        display: flex;
        align-items: center;
        gap: 8px;

        i {
          color: #409EFF;
        }
      }
    }

    .page-description {
      margin: 0;
      color: #606266;
      line-height: 1.6;
    }
  }

  .el-card {
    margin-bottom: 20px;
    border: none;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;

      span {
        display: flex;
        align-items: center;
        gap: 6px;

        i {
          color: #409EFF;
        }
      }
    }
  }

  .config-card {
    .config-item {
      margin-bottom: 12px;
      display: flex;
      align-items: center;
      gap: 8px;

      label {
        font-weight: 500;
        color: #606266;
        min-width: 100px;
      }
    }
  }

  // 确保表单项标签和控件在同一行
  .test-panel-card {
    ::v-deep .el-form-item {
      margin-bottom: 18px;

      .el-form-item__label {
        white-space: nowrap;
        flex-shrink: 0;
      }

      .el-form-item__content {
        flex: 1;
        min-width: 0;
      }
    }
  }

  .batch-test-case {
    border: 1px solid #EBEEF5;
    border-radius: 4px;
    padding: 16px;
    margin-bottom: 12px;
    background-color: #FAFBFC;

    .test-case-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      font-weight: 500;
    }
  }

  .batch-test-actions {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .test-case-count {
      color: #909399;
      font-size: 14px;
    }
  }

  .empty-batch-test {
    text-align: center;
    padding: 40px;
    color: #909399;

    i {
      font-size: 48px;
      margin-bottom: 16px;
      display: block;
    }

    p {
      margin: 0 0 16px 0;
      font-size: 16px;
    }
  }

  .test-result-content {
    .result-status {
      margin-bottom: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .execution-time {
        color: #909399;
        font-size: 14px;
      }
    }

    .json-content {
      background-color: #F5F7FA;
      padding: 16px;
      border-radius: 4px;
      border: 1px solid #EBEEF5;
      font-family: 'Courier New', monospace;
      font-size: 12px;
      line-height: 1.5;
      max-height: 400px;
      overflow-y: auto;
      white-space: pre-wrap;
      word-break: break-all;
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    text-align: center;
  }
}

// 测试详情弹窗样式
::v-deep .test-detail-dialog {
  width: 90% !important;
  max-width: 1200px !important;
  min-width: 800px !important;
  
  .el-message-box {
    width: 100% !important;
  }
  
  .el-message-box__content {
    overflow: hidden;
  }
  
  .el-message-box__message {
    max-height: 70vh;
    overflow-y: auto;
    overflow-x: hidden;
    
    pre {
      background-color: #F5F7FA;
      padding: 16px;
      border-radius: 4px;
      border: 1px solid #EBEEF5;
      font-family: 'Courier New', monospace;
      font-size: 12px;
      line-height: 1.5;
      white-space: pre-wrap;
      word-wrap: break-word;
      overflow-wrap: break-word;
      margin: 0;
      width: 100%;
      box-sizing: border-box;
    }
  }
}
</style>

<style lang="scss">
// 全局样式，确保测试详情弹窗正确显示
.test-detail-dialog {
  width: 90% !important;
  max-width: 1200px !important;
  min-width: 800px !important;
  
  .el-message-box {
    width: 100% !important;
  }
  
  .el-message-box__content {
    overflow: hidden !important;
  }
  
  .el-message-box__message {
    max-height: 70vh !important;
    overflow-y: auto !important;
    overflow-x: hidden !important;
    
    pre {
      background-color: #F5F7FA !important;
      padding: 16px !important;
      border-radius: 4px !important;
      border: 1px solid #EBEEF5 !important;
      font-family: 'Courier New', monospace !important;
      font-size: 12px !important;
      line-height: 1.5 !important;
      white-space: pre-wrap !important;
      word-wrap: break-word !important;
      overflow-wrap: break-word !important;
      margin: 0 !important;
      width: 100% !important;
      box-sizing: border-box !important;
    }
  }
}
</style>